<?php

namespace app\controller\customer;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use think\facade\Validate;

/**
 * 客户会员管理
 */
class Membership extends BaseController
{
    /**
     * 获取会员列表
     */
    public function list()
    {
        $params = Request::param();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 20;
        $customerId = $params['customer_id'] ?? 0;
        $status = $params['status'] ?? '';

        $query = Db::name('customer_membership')
            ->alias('m')
            ->field('m.*, c.name as enterprise_name')
            ->leftJoin('customer c', 'm.customer_id = c.id')
            ->where('m.id', '>', 0);

        if ($customerId) {
            $query->where('m.customer_id', $customerId);
        }

        if ($status !== '') {
            $query->where('m.status', $status);
        }

        $total = $query->count();
        $list = $query->order('m.create_time', 'desc')
            ->page($page, $limit)
            ->select();

        return $this->paginate($list ? $list->toArray() : [], $total, (int)$page, (int)$limit);
    }

    /**
     * 获取会员统计数据
     */
    public function stats()
    {
        // 总会员数
        $total = Db::name('customer_membership')->where('id', '>', 0)->count();

        // 生效中会员数
        $active = Db::name('customer_membership')
            ->where('status', 1)
            ->where('service_end_date', '>', time())
            ->count();

        // 已过期会员数
        $expired = Db::name('customer_membership')
            ->where('status', 'in', [1, 2])
            ->where('service_end_date', '<=', time())
            ->count();

        // 冻结会员数
        $frozen = Db::name('customer_membership')
            ->where('status', 3)
            ->count();

        // 即将过期会员数（30天内）
        $aboutToExpire = Db::name('customer_membership')
            ->where('status', 1)
            ->where('service_end_date', '>', time())
            ->where('service_end_date', '<=', time() + 30 * 24 * 3600)
            ->count();

        return $this->success([
            'total' => $total,
            'active' => $active,
            'expired' => $expired,
            'frozen' => $frozen,
            'about_to_expire' => $aboutToExpire
        ]);
    }

    /**
     * 获取会员详情
     */
    public function detail()
    {
        $id = Request::param('id');
        if (!$id) {
            return $this->error('参数错误');
        }

        $membership = Db::name('customer_membership')
            ->alias('m')
            ->field('m.*, c.name as enterprise_name, ma.customer_name as main_account_name')
            ->leftJoin('customer c', 'm.customer_id = c.id')
            ->leftJoin('customer_account ma', 'm.main_account_id = ma.customer_id')
            ->where('m.id', $id)
            ->find();

        if (!$membership) {
            return $this->error('会员记录不存在');
        }

        return $this->success($membership);
    }

    /**
     * 开通会员
     */
    public function create()
    {
        $params = Request::param();

        // 参数验证
        $validate = Validate::rule([
            'customer_id|客户ID' => 'require|number',
            'enterprise_name|企业名称' => 'require',
            'membership_type|会员类型' => 'require|in:1,2,3',
            'account_type|账户类型' => 'require|in:1,2',
            'main_account_id|主账户ID' => 'number',
            'service_start_date|服务开始日期' => 'require',
            'service_end_date|服务结束日期' => 'require'
        ]);

        if (!$validate->check($params)) {
            return $this->error($validate->getError());
        }

        // 检查客户是否存在且为企业客户
        $customer = Db::name('customer')->where('id', $params['customer_id'])->find();
        if (!$customer) {
            return $this->error('客户不存在');
        }

        if ($customer['customer_type'] != 16) {
            return $this->error('会员开通仅限企业客户');
        }

        // 如果是子账号，需要检查主账号是否存在
        if ($params['account_type'] == 2) {
            if (!$params['main_account_id']) {
                return $this->error('子账号必须关联主账号');
            }

            $mainAccount = Db::name('customer_membership')
                ->where('id', $params['main_account_id'])
                ->where('account_type', 1)
                ->find();

            if (!$mainAccount) {
                return $this->error('主账号不存在');
            }

            // 检查主账号是否在服务期内
            if ($mainAccount['service_end_date'] <= time()) {
                return $this->error('主账号服务已过期，无法开通子账号');
            }
        }

        $data = [
            'customer_id' => $params['customer_id'],
            'enterprise_name' => $params['enterprise_name'],
            'membership_type' => $params['membership_type'],
            'account_type' => $params['account_type'],
            'main_account_id' => $params['account_type'] == 2 ? $params['main_account_id'] : null,
            'service_start_date' => strtotime($params['service_start_date']),
            'service_end_date' => strtotime($params['service_end_date']),
            'status' => 1,
            'order_id' => $params['order_id'] ?? null,
            'create_time' => time(),
            'update_time' => time()
        ];

        $id = Db::name('customer_membership')->insertGetId($data);

        if ($id) {
            // 如果是主账号，创建对应的客户账号
            if ($params['account_type'] == 1) {
                $this->createCustomerAccount($params['customer_id'], $params['enterprise_name']);
            }

            // 更新客户属性为会员
            Db::name('crm_customer')->where('id', $params['customer_id'])->update([
                'customer_attribute' => 3,
                'customer_status' => 2,
                'member_type' => $params['membership_type'],
                'member_start_time' => $data['service_start_date'],
                'member_end_time' => $data['service_end_date'],
                'is_main_account' => $params['account_type'],
                'main_account_id' => $data['main_account_id']
            ]);

            return $this->success(['id' => $id], '开通成功');
        }

        return $this->error('开通失败');
    }

    /**
     * 延长会员期限
     */
    public function extend()
    {
        $params = Request::param();

        $validate = Validate::rule([
            'id|会员记录ID' => 'require|number',
            'service_end_date|服务结束日期' => 'require'
        ]);

        if (!$validate->check($params)) {
            return $this->error($validate->getError());
        }

        $membership = Db::name('customer_membership')->where('id', $params['id'])->find();
        if (!$membership) {
            return $this->error('会员记录不存在');
        }

        $result = Db::name('customer_membership')->where('id', $params['id'])->update([
            'service_end_date' => strtotime($params['service_end_date']),
            'status' => 1,
            'update_time' => time()
        ]);

        if ($result !== false) {
            // 更新客户表中的会员信息
            Db::name('crm_customer')->where('id', $membership['customer_id'])->update([
                'member_end_time' => strtotime($params['service_end_date'])
            ]);

            return $this->success([], '延长成功');
        }

        return $this->error('延长失败');
    }

    /**
     * 冻结会员
     */
    public function freeze()
    {
        $id = Request::param('id');
        if (!$id) {
            return $this->error('参数错误');
        }

        $result = Db::name('customer_membership')->where('id', $id)->update([
            'status' => 3,
            'update_time' => time()
        ]);

        if ($result !== false) {
            return $this->success([], '冻结成功');
        }

        return $this->error('冻结失败');
    }

    /**
     * 解冻会员
     */
    public function unfreeze()
    {
        $id = Request::param('id');
        if (!$id) {
            return $this->error('参数错误');
        }

        $membership = Db::name('customer_membership')->where('id', $id)->find();
        if (!$membership) {
            return $this->error('会员记录不存在');
        }

        // 检查服务期是否已过期
        if ($membership['service_end_date'] <= time()) {
            return $this->error('会员服务已过期，无法解冻');
        }

        $result = Db::name('customer_membership')->where('id', $id)->update([
            'status' => 1,
            'update_time' => time()
        ]);

        if ($result !== false) {
            return $this->success([], '解冻成功');
        }

        return $this->error('解冻失败');
    }

    /**
     * 获取客户的会员信息
     */
    public function getCustomerMembership()
    {
        $customerId = Request::param('customer_id');
        if (!$customerId) {
            return $this->error('参数错误');
        }

        $membership = Db::name('customer_membership')
            ->where('customer_id', $customerId)
            ->where('status', 'in', [1, 2])  // 生效或过期
            ->order('create_time', 'desc')
            ->select();

        return $this->success($membership ? $membership->toArray() : []);
    }

    /**
     * 检查会员是否在服务期内
     */
    public function checkServicePeriod()
    {
        $customerId = Request::param('customer_id');
        if (!$customerId) {
            return $this->error('参数错误');
        }

        $membership = Db::name('customer_membership')
            ->where('customer_id', $customerId)
            ->where('status', 1)
            ->where('service_end_date', '>', time())
            ->find();

        if ($membership) {
            return $this->success([
                'is_member' => true,
                'membership' => $membership
            ]);
        }

        return $this->success([
            'is_member' => false,
            'membership' => null
        ]);
    }

    /**
     * 创建客户账号（主账号）
     */
    private function createCustomerAccount($customerId, $customerName)
    {
        // 检查是否已经存在账号
        $exists = Db::name('customer_account')->where('customer_id', $customerId)->count();
        if ($exists > 0) {
            return true;
        }

        // 使用手机号作为账号，如果没有手机号则使用客户ID生成
        $customer = Db::name('customer')->where('id', $customerId)->find();
        $mobile = $customer['name'] . $customerId; // 临时使用客户名+ID作为账号

        $salt = randStr(10);
        $password = md5('123456' . $salt);  // 临时密码为123456

        Db::name('customer_account')->insert([
            'mobile' => $mobile,
            'password' => $password,
            'salt' => $salt,
            'customer_id' => $customerId,
            'customer_name' => $customerName,
            'status' => 1,
            'create_time' => time(),
            'update_time' => time()
        ]);

        return true;
    }
}

/**
 * 生成随机字符串
 */
function randStr($length = 10)
{
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $str = '';
    for ($i = 0; $i < $length; $i++) {
        $str .= $chars[rand(0, strlen($chars) - 1)];
    }
    return $str;
}
